
import * as path from 'path';
import * as fs from 'fs';
import * as vscode from 'vscode';


export class ChatPanel {
  public static currentPanel: ChatPanel | undefined;
  public readonly panel: vscode.WebviewPanel;
  private disposables: vscode.Disposable[] = [];

  public constructor(panel: any) {
    this.panel = panel;
    this.panel.onDidDispose(() => this.dispose(), null, this.disposables);
    this.panel.webview.html = this.getWebviewContent();
  }

  public static createOrShow() {
    const column = vscode?.window?.activeTextEditor
      ? vscode?.window?.activeTextEditor.viewColumn
      : undefined;

    if (ChatPanel.currentPanel) {
      ChatPanel.currentPanel.panel.reveal(column);
      return;
    }

    const panel = vscode.window.createWebviewPanel(
      'HephaestusChat',
      'Hephaestus AI Assistant',
      column || vscode.ViewColumn.One,
      {
        enableScripts: true,
      }
    );

    ChatPanel.currentPanel = new ChatPanel(panel);
  }

  private getWebviewContent() {
    const htmlPath = path.join(__dirname, '..', '..', 'src', 'ui', 'chat.html');
    let htmlContent = fs.readFileSync(htmlPath, 'utf-8');

    // 处理资源路径
    const assetsPath = path.join(__dirname, '..', '..', 'resources');
    const webviewUri = this.panel.webview.asWebviewUri(vscode.Uri.file(assetsPath));

    // 替换资源路径
    htmlContent = htmlContent.replace(
      /\${webviewUri}/g,
      webviewUri.toString()
    );
    return htmlContent;

    // const vueCdnUrl = 'https://cdn.jsdelivr.net/npm/vue@3.3.11/dist/vue.global.prod.js';
    // return `
    //     <!DOCTYPE html>
    //     <html lang="en">
    //     <head>
    //         <meta charset="UTF-8">
    //         <meta name="viewport" content="width=device-width, initial-scale=1.0">
    //         <title>Vue Webview</title>
    //     </head>
    //     <body>
    //         <div id="app">
    //             {{ message }}
    //         </div>
    //         <script src="${vueCdnUrl}"></script>
    //         <script>
    //             const { createApp } = Vue;
    //             const app = createApp({
    //                 data() {
    //                     return {
    //                         message: 'Hello, Vue 3 in Webview!'
    //                     };
    //                 }
    //             });
    //             app.mount('#app');
    //         </script>
    //     </body>
    //     </html>
    // `;
  }

  private dispose() {
    ChatPanel.currentPanel = undefined;
    this.panel.dispose();
    while (this.disposables.length) {
      const x = this.disposables.pop();
      if (x) {
        x.dispose();
      }
    }
  }
}